/**
 * Copyright (c) 2015-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.core.plugin.shiro;

import com.jfinal.kit.Ret;
import io.jboot.Jboot;
import io.jplus.JplusConsts;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * Created by Administrator on 2017/12/29.
 */
public class SSOAuthRealm extends AuthorizingRealm {

    private ShiroService shiroService = Jboot.service(ShiroService.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return shiroService.buildAuthorizationInfo(principals);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Ret ret = shiroService.shiroLogin(token.getUsername(), new String(token.getPassword()));
        String errorCode = ret.getStr("code");
        if (JplusConsts.LOGIN_FAIL_USER.equals(errorCode)) {
            throw new UnknownAccountException(ret.getStr(JplusConsts.RET_MSG));
        }
        if (JplusConsts.LOGIN_FAIL_PWD.equals(errorCode)) {
            throw new AccountException(ret.getStr(JplusConsts.RET_MSG));
        }
        if (errorCode != null) {
            throw new UnknownAccountException(ret.getStr(JplusConsts.RET_MSG));
        }
        return new SimpleAuthenticationInfo(token.getUsername(),
                new String(token.getPassword()), getName());
    }


}
